//
//  UserAccount.swift
//  weibo
//
//  Created by 陈伟 on 15/10/17.
//  Copyright © 2015年 陈伟. All rights reserved.
//

import UIKit

class UserAccount: NSObject, NSCoding {

    //字典转模型
    //
    var access_token: String?
    
    var expires_in: NSTimeInterval = 0 {
        //收到过期时间。计算准确的过期日期
        didSet{
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    //过期日期
    var expiresDate: NSDate?
    //用户ID
    var uid: String?
    //用户昵称
    var screen_name: String?
    
    //头像
    var avatar_large: String?
    
    //重载构造函数
    init(dict: [String: AnyObject]){
        super.init()
        
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) { }
    
    override var description: String{
        
        let keys = ["access_token", "expires_in", "uid", "screen_name", "avatar_large"]
        
        return dictionaryWithValuesForKeys(keys).description
    }
    
    func saveUserAccount() {
        var path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!
        
        //拼接路径
        path = (path as NSString).stringByAppendingPathComponent("account.plist")
        
//        print("归档路径" + path)
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
    }
    
    //归档解档实现两个方法
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expiresDate, forKey:"expiresDate")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(screen_name, forKey: "screen_name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        uid = aDecoder.decodeObjectForKey("uid") as? String
        screen_name = aDecoder.decodeObjectForKey("screen_name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
}
